package com.yeyks.commonReference.append.yedun;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yeyks.common.utils.SystemStrackUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@ConditionalOnProperty(prefix = "yyks.yedun", name = "enable", havingValue = "true")
@Slf4j
public class YeDunService {

    @Autowired
    private YeDunProperties yeDunProperties;
    /**
     * 本机认证服务身份证实人认证在线检测接口地址
     */
    private final static String API_URL = "https://ye.dun.163yun.com/v1/oneclick/check";


    /*
    http://support.dun.163.com/documents/287305921855672320?docId=288803729972580352&locale=zh-cn
     */
    public String getPhone(String accessCode, String token) {
        String phone = null;
        String response = "";
        try {
            Map<String, String> params = new HashMap<String, String>();
            // 1.设置公共参数
            params.put("secretId", yeDunProperties.getSecretId());
            params.put("businessId", yeDunProperties.getBusinessId());
            params.put("version", "v1");
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            //32随机字符串
            params.put("nonce", RandomUtil.randomString(32));
            // 2.设置私有参数
            params.put("accessToken", accessCode);
            params.put("token", token);
            // 3.生成签名信息
            String signature = genSignature(yeDunProperties.getSecretKey(), params);
            params.put("signature", signature);
            // 4.发送HTTP请求
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            BeanUtil.copyProperties(params, stringObjectHashMap);
            response = HttpUtil.post(API_URL, stringObjectHashMap);
            //5.解析报文返回
            ApiResponse apiResponse = JSONUtil.toBean(response, ApiResponse.class);
            //6.返回结果
            phone = apiResponse.getData().getPhone();
        } catch (Exception e) {
            SystemStrackUtil.logYyksExceptionStack(e);
            log.error("一键登录失败,参数:accessCode:{}-----token:{}-----response:{}", accessCode, token, response);
        }
        return phone;
    }

    /**
     * 生成签名信息
     *
     * @param secretKey 产品私钥
     * @param params    接口请求参数名和参数值map，不包括signature参数名
     * @return
     */
    public static String genSignature(String secretKey, Map<String, String> params) {
        // 1. 参数名按照ASCII码表升序排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 2. 按照排序拼接参数名与参数值
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append(params.get(key));
        }
        // 3. 将secretKey拼接到最后
        sb.append(secretKey);

        // 4. MD5是128位长度的摘要算法，转换为十六进制之后长度为32字符
        return DigestUtil.md5Hex(sb.toString(), CharsetUtil.UTF_8);
    }

}
